package com.zwb.service.filter;

import com.alibaba.fastjson.JSON;
import com.zwb.service.enums.StatusCode;
import com.zwb.service.exception.TokenAuthenticationException;
import com.zwb.service.common.JwtTokenUtil;
import com.zwb.service.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 头发又黑又长
 * @Date 2022/8/27 14:53
 * @email zwb15083976291@163.com
 */

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            this.tokenAuthentication(request, response);
            filterChain.doFilter(request, response);
        } catch (TokenAuthenticationException e) {
            this.authenticationFailed(request, response, e);
        } catch (Exception e) {
            throw e;
        }
    }

    private void tokenAuthentication(HttpServletRequest request, HttpServletResponse response) {
        String header = request.getHeader(tokenHeader);
        if (ObjectUtils.isEmpty(header)) {
            return;
        }
        //不以 tokenHead 为开头
        if (!header.startsWith(tokenHead)) {
            return;
        }
        // 获取token
        String token = header.substring(tokenHead.length());
        // token 判断
        JwtTokenUtil.TokenStatus tokenStatus = jwtTokenUtil.validateToken(token);
        if (tokenStatus != JwtTokenUtil.TokenStatus.SUCCESS) {
            throw new TokenAuthenticationException(tokenStatus.getMessage());
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(jwtTokenUtil.getUserName(token));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

    }

    /**
     * 如果token 错误，直接返回错误信息
     *
     * @param request
     * @param response
     * @param e
     * @throws IOException
     */
    private void authenticationFailed(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.result(e.getMessage(), StatusCode.AUTHORIZED)));
        response.getWriter().flush();
    }

}
